<template>
  <div class="blog-list">
    <div class="page-header">
      <h2>博客列表</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshBlogs">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索博客..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="selectedCategory" placeholder="选择分类" @change="handleCategoryChange">
            <el-option label="全部分类" value="" />
            <el-option 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="发布时间" value="publishTime" />
            <el-option label="点赞数" value="likeCount" />
            <el-option label="评论数" value="commentCount" />
            <el-option label="阅读数" value="viewCount" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="sortOrder" placeholder="排序顺序" @change="handleSort">
            <el-option label="最新" value="desc" />
            <el-option label="最早" value="asc" />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 博客列表 -->
    <div class="blogs-container">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
        <el-skeleton :rows="3" animated />
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="blogs.length === 0" class="empty-blogs">
        <el-empty description="暂无博客文章">
          <el-button type="primary" @click="$router.push('/blogmanagement')">
            去发布博客
          </el-button>
        </el-empty>
      </div>

      <div v-else class="blogs-grid">
        <div 
          v-for="blog in blogs" 
          :key="blog.id" 
          class="blog-item"
          @click="goToBlog(blog.id)"
        >
          <div class="blog-card">
            <div class="card-header">
              <div class="author-info">
                <el-avatar :src="blog.authorAvatar" :size="32">
                  {{ blog.authorName?.charAt(0) }}
                </el-avatar>
                <span class="author-name">{{ blog.authorName }}</span>
              </div>
              <div class="publish-time">
                {{ formatTime(blog.createdAt) }}
              </div>
            </div>

            <div class="card-content">
              <h3 class="blog-title">{{ blog.title }}</h3>
              <p class="blog-summary">{{ blog.summary }}</p>
              <div class="blog-tags" v-if="blog.tags && blog.tags.length > 0">
                <el-tag 
                  v-for="tag in blog.tags" 
                  :key="tag" 
                  size="small" 
                  type="info"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>

            <div class="card-footer">
              <div class="blog-stats">
                <span class="stat-item">
                  <el-icon><View /></el-icon>
                  {{ blog.viewCount }}
                </span>
                <span class="stat-item">
                  <el-icon><Top /></el-icon>
                  {{ blog.likeCount }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ blog.commentCount }}
                </span>
              </div>
              <div class="blog-category">
                <el-tag size="small" type="primary">
                  {{ blog.categoryName }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh, Search, View, Top, ChatDotRound } from '@element-plus/icons-vue'
import { blogList, classList } from '@/api/blog'

const router = useRouter()

// 状态数据
const loading = ref(false)
const blogs = ref([])
const categories = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 筛选和搜索
const searchKeyword = ref('')
const selectedCategory = ref('')
const sortBy = ref('publishTime')
const sortOrder = ref('desc')

// 加载博客列表
const loadBlogs = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
      categoryId: selectedCategory.value,
      sortBy: sortBy.value,
      sortOrder: sortOrder.value
    }
    
    const res = await blogList(params)
    if (res.success) {
      blogs.value = res.data.list || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取博客列表失败')
  } finally {
    loading.value = false
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await classList()
    if (res.success) {
      categories.value = res.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 刷新博客列表
const refreshBlogs = () => {
  currentPage.value = 1
  loadBlogs()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadBlogs()
}

// 处理分类变化
const handleCategoryChange = () => {
  currentPage.value = 1
  loadBlogs()
}

// 处理排序
const handleSort = () => {
  currentPage.value = 1
  loadBlogs()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadBlogs()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadBlogs()
}

// 跳转到博客详情
const goToBlog = (blogId) => {
  router.push(`/blog/${blogId}`)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return date.toLocaleDateString()
}

onMounted(() => {
  loadCategories()
  loadBlogs()
})
</script>

<style scoped>
.blog-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
}

.filter-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.blogs-container {
  margin-bottom: 30px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.empty-blogs {
  padding: 60px 0;
  text-align: center;
}

.blogs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.blog-item {
  transition: transform 0.3s ease;
  cursor: pointer;
}

.blog-item:hover {
  transform: translateY(-2px);
}

.blog-card {
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
}

.blog-card:hover {
  border-color: #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.publish-time {
  font-size: 12px;
  color: #999;
}

.card-content {
  padding: 15px;
  flex: 1;
}

.blog-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.blog-summary {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 10px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.blog-tags {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.blog-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.stat-item .el-icon {
  font-size: 14px;
}

.blog-category {
  display: flex;
  gap: 5px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .blog-list {
    padding: 15px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .filter-section .el-row {
    margin: 0;
  }
  
  .filter-section .el-col {
    margin-bottom: 10px;
  }
  
  .blogs-grid {
    grid-template-columns: 1fr;
  }
  
  .card-footer {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .blog-stats {
    gap: 10px;
  }
}
</style> 